package com.homework.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * @author HLQ
 * @date 2024/10/11 10:29
 */
@Aspect
@Component
@Slf4j
public class LogAspect {
    /*
    point cut
     */
    @Pointcut("execution(public * com.homework.dao..*.*(..))")
    public void daoLayerAllMethods(){}

    @Pointcut("execution(public * com.homework.dao..*.insert*(..))")
    public void daoLayerMethodsStarWithInsert(){}

    /*
    advices
     */

    @Before("daoLayerAllMethods()")
    public  void simpleLogBeforeMethod(JoinPoint jp){
        log.info("method: " + jp.getSignature().getName() + "was ready for execution");
    }

    @After("daoLayerMethodsStarWithInsert()")
    public void afterAllInsertMethods(JoinPoint jp){
        log.info("method: " + jp.getSignature().getName() + "was invoked no matter" +
                "whether its calling was normal nor not.");
    }

    @Around("daoLayerAllMethods()")
    public Object measurePerformanceForAllDaoMethods(ProceedingJoinPoint pjp){

        //before
        Long start = System.currentTimeMillis();

        String methodName = pjp.getSignature().getName();
        Object ret = null;
        try{
            //调用原始方法
            ret = pjp.proceed();
        }catch(Throwable e){
            log.error("method: " + methodName + " met an error: " + e.getMessage());
        }

        //after
        Long end = System.currentTimeMillis();

        log.info("method: " + methodName + ", spent (s): " + (end - start) / 1000.0);
        return ret;
    }

}
